/*
 * Copyright (c) 2021 Huawei Device Co.,  Ltd.
 * Licensed under the Apache License,  Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,  software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,  either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "iccreader_observer_stub.h"
#include <string.h>
#include "message_option.h"
#include "message_parcel.h"
#include "iccreader_hilog.h"
#include "iccreader_common.h"
#include "iccreader_errors.h"

namespace SwanLink {
namespace Finance {
int IccReaderObserverStub::OnRemoteRequest(uint32_t code, MessageParcel& data,
        MessageParcel& reply, MessageOption& option) {
    ICCREADER_HILOGD(ICCREADER_SRV,  "IccReaderObserverStub::cmd = %{public}d,  flags = %{public}d",  code,  option.GetFlags());

    std::u16string descriptor = IccReaderObserverStub::GetDescriptor();
    std::u16string remoteDescriptor = data.ReadInterfaceToken();
    if (descriptor != remoteDescriptor) {
        ICCREADER_HILOGE(ICCREADER_SRV,  "IccReaderObserverStub::Descriptor is not matched");
        return ERR_NAME_NOT_FOUND;
    }
    if (code == ICCREADER_OBSERVER_ID_ONSUCCESS) {
        return OnResultStub(data, reply);
    } else if (code == ICCREADER_OBSERVER_ID_ONERROR) {
        return OnErrorStub(data, reply);
    }
    return 0;
}

int IccReaderObserverStub::OnResultStub( MessageParcel& data,
        MessageParcel& reply) {
    int status = 0;
    ResultData *result = NULL;
    READ_PARCEL_WITH_RET(data, Int32, status, E_READ_PARCEL_ERROR);
    READ_BUFFER_WITH_RET(data, ResultData, result, sizeof(ResultData), E_READ_PARCEL_ERROR);
    if (result == NULL) {
        ICCREADER_HILOGE(ICCREADER_SRV,  "IccReaderObserverStub::OnResultStub failed");
        return E_READ_PARCEL_ERROR;
    }
    OnResult(status, *result);
    return ERR_OK;
}

int IccReaderObserverStub::OnErrorStub(MessageParcel& data,
        MessageParcel& reply) {
    int status = 0;
    std::string err;
    READ_PARCEL_WITH_RET(data, Int32, status, E_READ_PARCEL_ERROR);
    READ_PARCEL_WITH_RET(data, String, err, E_READ_PARCEL_ERROR);

    OnError(status, err);
    return ERR_OK;
}

}  // namespace Finance
}  // namespace SwanLink
